var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;

var MenuSchema = new mongoose.Schema({
	title:String,	//菜单名称
	url:String,		//菜单地址
	icon:String,	//菜单图标
	sort:Number,	//菜单排序
	isdel:Boolean,	//菜单是否被删除
	menu: {
		type:ObjectId,
		ref:'Menu'
	},
	menus:[
		{
			type:ObjectId,
			ref:'Menu'
		}
	],
	meta:{
		createAt:{
			type:Date,
			default:Date.now()
		},
		updateAt:{
			type:Date,
			default:Date.now()
		}
	}
});

MenuSchema.pre('save',function(next){
	// console.log('preSave');
	// if(!this.menu||this.menu==''){
    //   this.menu=null;
    // }
    // if(!this._id||this.menu==''){
    //   this._id=null;
    // }

	if(this.isNew){
		
		this.meta.createAt = this.meta.updateAt=Date.now();
		this.isdel = false;
	}else{
		this.meta.updateAt = Date.now();
	}
	next();
});

MenuSchema.statics = {
	fetch:function(cb){
		return this
			.find({isdel:false})
			//.sort('sort')
			.exec(cb);
	},
	findById:function(id,cb){
		return this
			.findOne({_id:id})
			.exec(cb);
	},
	delete:function(id,cb){
		console.log(id+"Delete");
		return this
			.findOne({_id:id})
			.remove();
	}
}

module.exports = MenuSchema;